package com.jk.framework.mybatis.handlers;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.jk.common.utils.ServletUtils;
import java.time.LocalDateTime;
import javax.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;

@Slf4j
public class BaseMetaObjectHandler implements MetaObjectHandler {

    public static final String CLIENT_NAME_KEY = "client";
    public static final String CLIENT_NAME_001 = "client001";

    @Override
    public void insertFill(MetaObject metaObject) {

        setFieldValByName("createBy", getUserName(), metaObject);
        setFieldValByName("deleted", "0", metaObject);
        setFieldValByName("createTime", LocalDateTime.now(), metaObject);

        setFieldValByName("updateBy", getUserName(), metaObject);
        setFieldValByName("updateTime", LocalDateTime.now(), metaObject);
    }


    @Override
    public void updateFill(MetaObject metaObject) {
        setFieldValByName("updateBy", getUserName(), metaObject);
        setFieldValByName("updateTime", LocalDateTime.now(), metaObject);
    }
/*
    protected LoginUser getLoginUser() {
        return SecurityUtils.getLoginUser();
    }*/


    protected String getUserName() {
        try {
            //return getLoginUser().getUsername();
            HttpServletRequest request = ServletUtils.getRequest();
            String client = request.getHeader(CLIENT_NAME_KEY);
            if (client == null) {
                client = request.getParameter(CLIENT_NAME_KEY);
            } else if (client == null) {
                client = CLIENT_NAME_001;
            }

            return client;
        } catch (Exception e) {
            log.warn(e.getMessage());
        }
        return "sys";

    }

}
